package com.aramis.mydytt.ui.dialog

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.aramis.mydytt.R
import com.aramis.mydytt.ext.dip
import com.aramis.mydytt.ui.bean.MovieDetailDownListBean
import com.aramis.mydytt.ui.bean.MovieField

/**
 * Description: DialogDownloadListAdapter
 * @author lizhidan
 * Created: 2021/5/10
 */
class DialogDownloadListAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    private val dataList = mutableListOf<MovieDetailDownListBean>()
    private var itemWidthDP = -1
    private var cate = 0
    var onItemClickListener: ((MovieDetailDownListBean) -> Unit)? = null

    fun setCate(cate: Int) {
        this.cate = cate
        itemWidthDP = if (cate == MovieField.CATE_MOVIE) 280 else 80
    }

    fun setData(list: List<MovieDetailDownListBean>?) {
        dataList.clear()
        list?.apply { dataList.addAll(this) }
        notifyDataSetChanged()
    }

    override fun getItemViewType(position: Int): Int {
        return if (dataList[position].fromDytt) 1 else 0
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(
                if (viewType == 1) R.layout.item_detail_download_list_dytt else R.layout.item_detail_download_list,
                parent, false
            )
        return if (viewType == 1) DyttViewHolder(view) else ViewHolder(view)
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val bean = dataList[position]
        if (holder is DyttViewHolder) {
            holder.textView.text = bean.title
            holder.textView.setOnClickListener {
                onItemClickListener?.invoke(bean)
            }
        } else {
            val normalHolder = holder as ViewHolder
            normalHolder.textView.text = bean.title
            if (itemWidthDP > 0 && holder.textView.layoutParams != null) {
                normalHolder.textView.layoutParams.width = holder.textView.context.dip(itemWidthDP)
            }
            normalHolder.textView.setOnClickListener {
                onItemClickListener?.invoke(bean)
            }
        }
    }

    override fun getItemCount(): Int = dataList.size

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val textView: TextView = itemView.findViewById(R.id.text_download_item)
    }

    class DyttViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val textView: TextView = itemView.findViewById(R.id.text_download_item)
    }
}